<?php
/*********************************************************************\
*  Copyright (c) 1998-2013, TH. All Rights Reserved.
*  Author :wuyou
*  FName  :Product.php
*  Time   :2019/02/14 16:30:13
*  Remark :产品档案
\*********************************************************************/
FLEA::loadClass('TMIS_Controller');
class Controller_Jichu_Product extends TMIS_Controller {
    var $funcId = '90-4';
    /**
     * 构造函数
     * @var 参数类型
    */
    function __construct(){
        $this->_modelExample = FLEA::getSingleton('Model_Jichu_Product');
        $this->_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');
        $this->simImage = FLEA::getAppInf('searchByImage');
    }

    /**
     * 导航进入产品大类
     * Time：2019/05/06 10:04:41
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionIndex(){
        $proKinds = $this->_modelKind->findAll();
        $smarty = & $this->_getView();
        $smarty->assign('title','产品档案');
        $smarty->assign('proKinds',$proKinds);
        $smarty->display('Jichu/ProductIndex.tpl');
    }


    /**
     * 角色html配置form
     * Time：2018/12/13 15:49:40
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    public function buildHtml($kind) {
        $fileds = $this->_modelKind->getFileds($kind ,'all');
        // dump($fileds);
        $params = array();
        $params['formItems'] = array(
            array(
                'type'      =>'comp-select',
                'name'      =>'kindId',
                'title'     =>'产品大类',
                'clearable' =>true,
                'disabled'  =>true,
                'options'   =>$this->_modelKind->getOptions(),
                'value'     =>'',
            ),
            array(
                'type'      =>'comp-text',
                'name'      =>'proCode',
                'title'     =>'产品编号',
                'clearable' =>true,
                'value'     =>'',
                'addonEnd'  =>'不建议使用中文和特殊符号，条码不支持',
            ),
            array(
                'type'      =>'comp-text',
                'name'      =>'proName',
                'title'     =>'产品名称',
                'clearable' =>true,
                'value'     =>'',
            ),
        );

        //加载个性的部分
        if($fileds){
            foreach ($fileds as $key => $v) {
                if($v['type'] == 'autocomplete'){
                    $params['formItems'][] = array(
                        'type'       =>'comp-autocomplete',
                        'name'       =>$v['filed'],
                        'title'      =>$v['title'],
                        'value'      =>'',
                        'clearable'  =>false,
                        'options'    =>$this->_modelExample->getColumnValues($v['filed'] ,$v['kindId']),
                        'placeholder' =>'可输入可选择历史记录',
                    );
                }else{
                    $params['formItems'][] = array(
                        'type'      =>'comp-text',
                        'name'      =>$v['filed'],
                        'title'     =>$v['title'],
                        'clearable' =>true,
                        'value'     =>'',
                    );
                }
            }
        }
        // dump($params);exit;
        $params['formItems'][] = array(
                'type'         =>'comp-image',
                'name'         =>'pic',
                'title'        =>'产品图片',
                'action'       =>$this->_url('UploadImage'),//上传地址
                'actionRemove' =>$this->_url('RemoveImage'),//删除图片时需要从服务器删除,可以不定义
                'accept'       =>'.jpg,.bmp,.png',//接受上传的文件类型
                'limit'        =>5,//最大允许上传个数
                'multiple'     =>true,//是否允许多选,
            );
        // if($this->simImage){
        //     $params['formItems'][] = array(
        //         'type'      =>'comp-select',
        //         'name'      =>'isSim',
        //         'title'     =>'用于图片搜索',
        //         'clearable' =>true,
        //         // 'disabled'  =>true,
        //         'options'   =>array(
        //             array('value'=>'1','text'=>'允许搜索'),
        //             array('value'=>'0','text'=>'禁止搜索'),
        //         ),
        //         'value'     =>'',
        //     );
        // }

        $params['formItems'][] = array(
                'type'      =>'comp-textarea',
                'name'      =>'memo',
                'title'     =>'备注',
                'clearable' =>true,
                'value'     =>'',
            );

        $params['rules'] = array(
            'proCode'=>array(
                array(
                    'required'=>true,
                    'message'=>'产品编号必须',
                )
            ),
            'proName'=>array(
                array(
                    'required'=>true,
                    'message'=>'产品名称必须',
                )
            )
        );

        if($fileds){
            foreach ($fileds as $key => $v) {
                if($v['isRequire'] == 'on'){
                    $params['rules'][$v['filed']] = array(
                        array('required'=>true,'message'=>"{$v['title']}"."必须"),
                    );
                }
            }
        }
        return $params;
    }


    /**
     * @desc ：产品查询
     * Time：2019/02/14 16:49:06
     * @author Wuyou
    */
    function actionRight() {
        $this->authCheck(0);
        $initKindid = $_GET['kindId'].'';

        $searchItems = array(
            'key'       =>'',
            'isSample'  =>'',
            'kindIdGet' =>$initKindid,
        );
        $smarty = & $this->_getView();

        $editButtons = array(
            array('text'=>'修改','type'=>'redirect','icon'=>'el-icon-edit','options'=>array(
                'url'            =>$this->_url('Edit').'&id={id}',
                'disabledColumn' =>'__disabledEdit',
            )),
            array('text'=>'删除','type'=>'remove','options'=>array(
                'url'            =>$this->_url('RemoveAjax'),
                'disabledColumn' =>'__disabledRemove',
            )),
            array('text'=>'上架/下架','type'=>'func','icon'=>'el-icon-check','options'=>array(
                'disabledColumn' =>'__disabledOver',
                'funcName'       =>"FuncIsover",
            )),
        );

        $arrFieldInfo = array(
            "kindName"     =>array('text'=>"产品类别",'width'=>'110','editButtons'=>$editButtons,'showButton'=>true),
            "proCode"      =>array('text'=>"产品编号",'width'=>'110','forKeySearch'=>true),
            "proName"      =>array('text'=>"产品名称",'width'=>'120','forKeySearch'=>true),
            "isSampleText" =>array('text'=>"是否上架",'width'=>'90','type'=>'html'),
            'preview'      =>array('text'=>"预览",'width'=>'70','type'=>'component','options'=>array(
                'type'=>'tip-preview-image',
            )),
        );

        if($this->simImage){
            $arrFieldInfo['isSim'] = array('text'=>"以图搜样品",'width'=>'100');
        }

        $fileds = $this->_modelKind->getFiledsKeyValueWidth($initKindid ,'all');
        // dump($fileds);exit;
        foreach ($fileds as $key => & $v) {
            $arrFieldInfo[$key] = array('text'=>$v['text'],'width'=>$v['width']);
        }

        // $arrFieldInfo['otherDesc'] = array('text'=>"其他描述",'width'=>'150','type'=>'html');
        $arrFieldInfo['memo'] = array('text'=>"备注",'width'=>'150');


        $smarty->assign('title', '产品列表');
        $smarty->assign('arr_field_info', $arrFieldInfo);
        $smarty->assign('action', $this->_url('GetRows'));
        $smarty->assign('searchItems', $searchItems);

        //循环所有的类
        $kinds = $this->_modelKind->findAll();
        // foreach ($kinds as & $v) {
        //     $menu[] = array('text'=>'新增'.$v['kindName'],'url'=>$this->_url('Add',array('kindId'=>$v['id'])),'icon'=>'el-icon-plus');
        // }

        // $kinds && $menu[] = array('text'=>'导入产品Excel','url'=>$this->_url('Index'),'icon'=>'el-icon-folder-checked') ;
        $kinds && $menu[] = array('text'=>'导入产品Excel','url'=>$this->_url('ImportFile',array('kindId'=>$initKindid)),'icon'=>'el-icon-folder-checked') ;
        $smarty->assign('menuRightTop', $menu);
        $smarty->assign('addUrl',$this->_url('Add',array('kindId'=>$initKindid)));
        $smarty->assign('sonTpl',array(
            'Jichu/TableProductList.js'
        ));
        $smarty->display('TableList_v1.1.tpl');
    }

    /**
     * 获取计划任务的数据
     * @author li
    */
    public function actionGetRows()  {
        FLEA::loadClass('TMIS_Common');
        $auth = $this->authCheck(0 ,true);

        if(!$auth){
            $ret = array(
              'total'   =>0,
              'columns' =>array(),
              'rows'    =>array(),
            );
            echo json_encode($ret);exit;
        }

        $post = $this->axiosPost();

        $pagesize    = $post['pagesize'];
        $currentPage = $post['currentPage'];

        $keyField    = isset($post['colForKey']) ? $post['colForKey'] : 'key';
        //处理搜索
        $post[$keyField] = $post['key'];
        if($keyField!='key') $post['key'] = '';

        $arr = $post;

        $sql = "SELECT x.*,y.kindName
                from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
                where 1";

        if($arr['key']!='') {
            $sql.=" and (x.proCode like '%{$arr['key']}%' or x.proName like '%{$arr['key']}%')";
        }
        if($arr['proCode']!='') {
            $sql.=" and x.proCode like '%{$arr['proCode']}%'";
        }
        if($arr['proName']!='') {
            $sql.=" and x.proName like '%{$arr['proName']}%'";
        }
        if($arr['isSample']!='') {
            $sql.=" and x.isSample = '{$arr['isSample']}'";
        }
        if($arr['kindId']) {
            $kindId = join(',' ,$arr['kindId']);
            $sql.=" and x.kindId in ({$kindId})";
        }
        if($arr['kindIdGet']) {
            $sql.=" and x.kindId = '{$arr['kindIdGet']}'";
        }

        $sql .=" order by id desc";
        // dump($sql);exit;
        FLEA::loadClass('TMIS_Pager');
        $pager = new TMIS_Pager($sql,null,null,$pagesize ,($currentPage - 1));
        $rowset = $pager->findAll();
        // dump($rowset);exit;
        foreach($rowset as & $v){
            //特殊处理下产品数据
            // $this->_modelExample->filedValue($v ,$filedsSingle);

            //把不需要单列的数据放在一列里展示
            // $v['otherDesc'] = $this->_modelExample->filedOtherFormat($v ,'html','' ,$filedsDefault);

            if($v['isSample'] == 1){
                $v['isSampleText'] = "<i class='el-icon-circle-check-outline'  style='color:#67C23A;' title='上架'>上架</i>";
            }else{
                $v['isSampleText'] = "<i class='el-icon-circle-close-outline'  style='color:#F56C6C;' title='下架'>下架</i>";
            }

            //图片预览
            if($v['pic']){
                $sql = "SELECT * from jichu_image where id in({$v['pic']})";
                $tmp = $this->_modelExample->findBySql($sql);
                // $tmp = array_col_values($tmp,'path');
                foreach ($tmp as & $ii) {
                    $v['imageSrc'][] = array(
                        'path'=>TMIS_Common::_imageSrc($ii['smallPath'])
                    );
                }
              }

            $v['isSim'] = $v['isSim']==0 ? '禁止搜索' : '允许搜索';
        }
        // dump($rowset);exit;

        $ret = array(
          'total'   =>$pager->totalCount,
          'columns' =>array(),
          'rows'    =>$rowset,
        );
        echo json_encode($ret);exit;
    }

    /**
     * 新增
     * Time：2018/12/17 13:35:37
     * @author li
    */
    function actionAdd() {
        $this->authCheck($this->funcId);
        $this->_edit(array('kindId'=>$_GET['kindId']));
    }

    /**
     * 编辑修改
     * Time：2018/12/17 13:36:35
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionEdit() {
        $this->authCheck($this->funcId);
        $row = $this->_modelExample->find($_GET['id']);
        $pic = explode(',', $row['pic']);
        $imgs = array();
        foreach ($pic as & $v) {
            if(!$v)continue;
            $sql = "SELECT * FROM jichu_image WHERE id='{$v}'";
            $temp = $this->_modelExample->findBySql($sql);
            $imgs[] = array(
                'imageId' => $v,
                'name'    => 'image_'.$v,
                'url'     => $temp[0]['path']
            );
        }
        $row['pic'] = $imgs;
        // dump($pic);exit;
        $this->_edit($row);
    }

    function _edit($Arr = array()) {
        $formParams = $this->buildHtml($Arr['kindId']);
        if(!$Arr){
            foreach ($formParams['formItems'] as $key => $v) {
                $Arr[$v['name']] = $v['value'].'';
            }
        }
        $smarty = & $this->_getView();

        $smarty->assign('formItems',$formParams['formItems']);
        $smarty->assign('rules',$formParams['rules']);
        $smarty->assign('title','基本信息');
        $smarty->assign('row',$Arr);
        $smarty->assign('action',$this->_url('Save'));
        $smarty->display('MainForm.tpl');
    }

    /**
     * 档案保存
     * Time：2017/07/31 15:48:32
     * @author li
    */
    function actionSave() {
        $auth = $this->authCheck($this->funcId ,true);
        if(!$auth){
            $ret = array('msg'=>'登录权限过期','success'=>false);
            echo json_encode($ret);exit;
        }
        $post = $this->axiosPost();
        // dump($post);exit;

        //限制编号只能用数字加中英文
        $match = "/^[a-zA-Z0-9-_\/]*$/";
        if(!preg_match($match,$post['proCode'])){
            $ret = array('msg'=>'产品编号含有数字英文以外的字符','success'=>false);
            echo json_encode($ret);exit;
        }else{
            if(strlen($post['proCode']) < 5 || strlen($post['proCode']) > 20){
                $ret = array('msg'=>'产品编号字符长度5~20','success'=>false);
                echo json_encode($ret);exit;
            }
        }

        if(empty($post['id'])) {
            $condition = array();
            $condition[] = array('proCode',$post['proCode'],'=');
            $count = $this->_modelExample->findCount($condition);

            if($count > 0) {
                $ret = array('msg'=>'产品编号不能重复','success'=>false);
                echo json_encode($ret);exit;
            }
        } else {
            //修改时判断是否重复
            $condition = array();
            $condition[] = array('proCode',$post['proCode'],'=');
            $condition[] = array('id',$post['id'],'<>');
            $count = $this->_modelExample->findCount($condition);

            if($count > 0) {
                $ret = array('msg'=>'产品编号不能重复','success'=>false);
                echo json_encode($ret);exit;
            }
        }
        // 选择的图片
        if(count($post['pic']) > 0){
            $post['pic'] = join(',', array_col_values($post['pic'],'imageId'));
        }

        if($post['isSim'] != '0'){
            $post['isSim'] = $this->simImage ? 1 : 0;
        }

        $result = $this->_modelExample->save($post);
        if($result){
            $ret = array(
                'success' =>true,
                'msg'     =>'操作成功',
            );
            $ret['targetUrl'] = $this->_url('Right',array('kindId'=>$post['kindId']));
        }else{
            $ret = array(
                'success' =>false,
                'msg'     =>'操作失败',
            );
        }

        echo json_encode($ret);exit;
    }

    //删除图片或者文件 TODO
    function actionRemoveFile() {
        $requestParam = file_get_contents('php://input');
        $_POST = json_decode($requestParam,true);

        $url = $_POST['url'];
        //根据url提取文件名,进行删除
        $ret = array(
          'success'=>true,
          'msg'=>'图片删除成功',
          'url'=>$url,
        );
        echo json_encode($ret);exit;
    }

    //获得产品列表页面：选择框
    function actionListPro() {
        $post = $this->axiosPost();

        $pagesize = $post['pagesize'];
        $currentPage = $post['currentPage'];

        $arr = $post;

        $sql="SELECT x.* ,y.kindName
                from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
                where isSample=1 ";
        if($arr['kindId']){
            $kindId = join(',',$arr['kindId']);
            $sql .= " and x.kindId in ({$kindId})";
        }

        if($arr['proCode']!='') {
            $sql.=" and x.proCode like '%{$arr['proCode']}%'";
        }
        if($arr['proName']!='') {
            $sql.=" and x.proName like '%{$arr['proName']}%'";
        }

        if($arr['key']!='') {
            $sql.=" and (
                x.filed1 like '%{$arr['key']}%'
                or x.filed2 like '%{$arr['key']}%'
                or x.filed3 like '%{$arr['key']}%'
                or x.filed4 like '%{$arr['key']}%'
                or x.filed5 like '%{$arr['key']}%'
                or x.filed6 like '%{$arr['key']}%'
                or x.filed7 like '%{$arr['key']}%'
                or x.filed8 like '%{$arr['key']}%'
                or x.filed9 like '%{$arr['key']}%'
                or x.filed10 like '%{$arr['key']}%'
            )";
        }
        $sql .=" order by id desc";
        // dump($sql);exit;
        FLEA::loadClass('TMIS_Pager');
        $pager = new TMIS_Pager($sql,null,null,$pagesize ,($currentPage - 1));
        $rowset = $pager->findAll();

        foreach ($rowset as $key => & $v) {
            //特殊处理下产品数据
            $this->_modelExample->filedValue($v ,$filedsSingle);

            //把不需要单列的数据放在一列里展示
            $v['otherDesc'] = $this->_modelExample->filedOtherFormat($v ,'string','' ,$filedsDefault);

            //处理需要展示的值
            $v['productDesc'] = $v['proCode'].' - '. $v['proName'];
            // if($filedsSingle[$v['kindId']]){
            //     foreach ($filedsSingle[$v['kindId']] as & $filed) {
            //         $v[$filed['filed']] && $v['otherShow'][] = $v[$filed['filed']].'';
            //     }
            //     $v['otherShow'] && $v['productDesc'] .= ' - '.join(' - ',$v['otherShow']);
            // }
        }

        //表头信息
        $fileds = $this->_modelKind->fileds2Table();
        foreach ($fileds as & $fv) {
            $fv = array('text'=>$fv ,'width'=>(mb_strlen($fv,'utf8')*18 > 80 ? mb_strlen($fv,'utf8')*18 : 80));
        }
        $arr_field_info = array_merge( array(
                // 'productDesc'  => array('text'=>'productDesc','width'=>'90'),
                'kindName'  => array('text'=>'大类','width'=>'90'),
                'proCode'   => array('text'=>'编号','width'=>'100'),
                'proName'   => array('text'=>'名称','width'=>'100'),
            )
            ,$fileds
            ,array(
                'otherDesc' => array('text'=>'其他描述','width'=>'150','type'=>'html'),
                'memo'      => array('text'=>'备注','width'=>'100'),
            )
        );

        $ret = array(
          'total'   =>$pager->totalCount,
          'columns' =>$arr_field_info,
          'rows'    =>$rowset,
          'searchItems'=>$this->getSearchItems(array('kindId','proCode','proName','key')),//暂不支持默认值
        );
        echo json_encode($ret);exit;
    }

    /**
     * 判断是否需要单位，单位有哪些
     * @var 参数类型
    */
    function actionUnit(){
        $post = $this->axiosPost();

        //查找产品id
        $productId = $post['productId'];
        $row = $this->_modelExample->find($productId);
        $res = $this->_modelExample->isUnit($row['kindId']);

        echo json_encode(array('_unit'=>$res,'unit'=>$row['unit']));
    }

    /**
     * @desc ：员工档案删除 验证是否已经被使用
     * Time：2017/07/31 15:49:06
     * @author lwj
    */
    function actionRemoveAjax() {
        $post = $this->axiosPost();
        $id = intval($post['row']['id']);

        //查找是否已经被使用
        $array = array(
            'Model_Sample_Chuku2Product' => 'productId',
            'Model_Sample_Ruku2Product'  => 'productId',
        );

        $isOccupy = false;

        foreach ($array as $key =>  & $v) {
            $tmpModel = FLEA::getSingleton($key);
            $condition = array();
            $condition[$v] = $id;
            $count = $tmpModel->findCount($condition);

            //如果某个表中存在，则不能删除
            if($count > 0){
                $isOccupy = true;
                $msg = $tmpModel->moduleName;
                break;
            }
        }

        if($isOccupy){
            $ret = array(
                'success' =>false,
                'msg'     =>'被'.$msg.'使用，禁止删除',
            );
            echo json_encode($ret);exit;
        }

        $oldInfo = $this->_modelExample->find($id);
        $res = $this->_modelExample->removeByPkv($id);

        if($res){
            //同时触发删除图片基础库的数据，物理删除图片文件
            if($oldInfo['pic']){
                $imgClass = FLEA::getSingleton('Controller_Jichu_Image');
                $image = explode(',', $oldInfo['pic']);
                foreach ($image as & $img) {
                    $imgClass->_removeImg($img);
                }
            }

            $ret = array(
                'success' =>true,
                'msg'     =>'删除成功',
            );
        }else{
            $ret = array(
                'success' =>false,
                'msg'     =>'删除失败',
            );
        }
        echo json_encode($ret);exit;
    }

    //是否上架
    function actionIsSample(){
        $post = $this->axiosPost();
        $id = intval($post['id']);

        $row = $this->_modelExample->find($id);
        $isSample = 1;
        if($row['isSample'] == 1){
            $isSample = 0;
        }

        $data = array(
            'id'       =>$id,
            'isSample' =>$isSample,
        );
        $res = $this->_modelExample->update($data);
        echo json_encode(array('msg'=>'操作完成','success'=>true));
    }

    /**
     * 导入excel中的客户新，使用的是csv文件
     * Time：2019/10/30 13:47:43
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionImportFile(){

        $arr = array();

        //获取分类信息
        $kind = $this->_modelKind->find($_GET['kindId']);
        $arr['kindId'] = $kind['id'];
        $kind['extendAttr'] = json_decode($kind['extendAttr'] ,true);
        $config = array(
            'proCode' =>'产品编号(英文和数组且长度大于5)',
            'proName' =>'产品名称',
        );
        foreach ($kind['extendAttr'] as & $v) {
            if($v['status'] == 'on' && $v['title']){
                $config[$v['filed']] = $v['title'];
            }
        }
        $config['memo'] = '备注';

        //需要把模版的字段写入到模版
        // $content = file_get_contents($path);
        $content = join(',' ,$config);
        $arr['filed'] = $config;
        // if(trim($content)){
        //     echo "当前有人在导入数据，请稍后操作";exit;
        // }
        $formParams = $this->buildHtmlImportantFile($kind ,$content);
        foreach ($formParams['formItems'] as & $v) {
            $arr[$v['name']] = $v['value'];
        }
        // dump($arr);
        // dump($config);
        // exit;

        $smarty = & $this->_getView();
        $smarty->assign('formItems',$formParams['formItems']);
        $smarty->assign('rules',$formParams['rules']);
        $smarty->assign('title',$kind['kindName']."导入数据");
        $smarty->assign('row',$arr);
        $smarty->assign('action',$this->_url('ConfirmData'));
        $smarty->display('MainForm.tpl');
    }

    /**
     * 角色html配置form
     * Time：2018/12/13 15:49:40
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    public function buildHtmlImportantFile($kind ,$content) {
        $params = array();
        $params['formItems'] = array(
            array(
                'type'      =>'comp-text',
                'name'      =>'template',
                'title'     =>'1.模版下载',
                'readonly'  =>true,
                'value'     =>'请先下载模版并整理好待上传的数据',
                'append'    =>'<a href="'.$this->_url('downloadFile',array('content'=>$content)).'" download="'.$kind['kindName'].'列表模版.csv" title="csv模版下载">csv最新模版下载</a>',
            ),
            array(
                'type'       =>'comp-file',
                'name'       =>'filePath',
                'title'      =>'2.上传csv',
                'buttonText' =>'开始上传附件',
                'action'     =>$this->_url('ImportFileData'),//上传地址
                'accept'     =>'.csv',//接受上传的文件类型
                'limit'      =>1,//最大允许上传个数
                'value'      =>'',
            ),
        );

        $params['rules'] = array(

        );

        return $params;
    }

    function actionDownloadFile(){
        $content = $_GET['content'];
        $path = 'Resource/Moban/jichu_product.csv';
        file_put_contents($path, iconv('UTF-8','GBK', $content));
        file_put_contents($path, iconv('UTF-8','GBK', "\n编号为英文和数组且长度5~20") , FILE_APPEND);
        // $newContent = file_get_contents($path);
        //设置头信息
        //声明浏览器输出的是字节流
        header('Content-Type: application/octet-stream');
        //声明浏览器返回大小是按字节进行计算
        header('Accept-Ranges:bytes');
        //告诉浏览器文件的总大小
        $fileSize = filesize($path);//坑 filesize 如果超过2G 低版本php会返回负数
        header('Content-Length:' . $fileSize); //注意是'Content-Length:' 非Accept-Length
        //声明下载文件的名称
        // header('Content-Disposition:attachment;filename=' . basename($path));//声明作为附件处理和下载后文件的名称

        //获取文件内容
        $handle = fopen($path, 'rb');//二进制文件用‘rb’模式读取
        while (!feof($handle) ) { //循环到文件末尾 规定每次读取（向浏览器输出为$readBuffer设置的字节数）
            echo fread($handle, 1024);
        }
        fclose($handle);//关闭文件句柄
        exit;
    }

    /**
     * 接收文档
     * Time：2019/10/30 14:37:53
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionImportFileData(){
        $file = $_FILES['filePath'];
        $pathinfo = pathinfo($file['name']);
        // dump($pathinfo);
        if(strtolower($pathinfo['extension']) != 'csv'){
            $ret = array('msg'=>'文件类型必须为CSV文件','success'=>false);
            echo json_encode($ret);exit;
        }

        $path = "upload/files/";
        $tmpname = $path.uniqid().rand(10000,99999).'.'.strtolower($pathinfo['extension']);
        move_uploaded_file($file['tmp_name'] ,$tmpname);

        $ret = array('msg'=>'完成上传','success'=>true,'filePath'=>$tmpname);
        echo json_encode($ret);exit;
    }

    /**
     * 确认数据
     * Time：2019/10/30 15:09:44
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionConfirmData(){
        $post = $this->axiosPost();
        // dump($post);exit;
        if(!$post['filePath']){
            $ret = array('msg'=>'还没有上传文件','success'=>false);
            echo json_encode($ret);exit;
        }

        //开始上传数据
        $msg = array();
        $fail = 0;
        foreach ($post['filePath'] as & $v) {
            if(!$v['url'] || !file_exists($v['url'])){
                continue;
            }
            //开始逐行读取数据
            $tmp = $this->readFileByLine($v['url'] ,array(
                'kindId' =>$post['kindId'],
                'filed'  =>$post['filed'],
            ));
            $fail += $tmp['fail'];
            $msg = array_merge($msg ,$tmp['msg']);
        }

        $ret = array('msg'=>join('<br/>',$msg),'success'=>($fail == 0));
        echo json_encode($ret);exit;

    }

    /**
   * 按行读取文件
   * @param string $filename
   */
  function readFileByLine($filename ,$params){
      $fh = fopen($filename, 'r');
      $data = array();
      $i = 0;
      $success = 0;
      $fail = 0;
      $msg = array();

      $params['filed'] = array_keys($params['filed']);

      while (! feof($fh)) {
          $line = fgets($fh);
          if($line){
            $i++;
            if($i == 1) continue;
            $tmp = explode(',', $line);

            $data = array();
            $data['kindId'] = $params['kindId'];
            foreach ($params['filed'] as $key => & $v) {
                $data[$v] = trim(iconv('GB2312', 'UTF-8', $tmp[$key]));
            }

            $t = array_filter($data);
            // dump($t);exit;
            if($t['proCode'] && $t['proName']){
                //限制编号只能用数字加中英文
                $match = "/^[a-zA-Z0-9-_\/]*$/";
                if(!preg_match($match,$data['proCode'])){
                    $fail++;
                    $msg[] = $data['proCode']."：编号含有数字英文以外的字符";
                    continue;
                }else{
                    if(strlen($data['proCode']) < 5 || strlen($data['proCode']) > 20){
                        $fail++;
                        $msg[] = $data['proCode']."：产品编号字符长度不符合5~20";
                        continue;
                    }
                }

                //判断是否重复了
                $isHave = $this->_modelExample->findCount(array('proCode'=>$data['proCode']));
                if($isHave){
                    $fail++;
                    $msg[] = $data['proCode']."：已经存在，导入失败<br/>";
                    continue;
                }

                //不重复则开始保存
                $id = $this->_modelExample->save($data);
                if($id > 0){
                  $success++;
                }else{
                  $fail++;
                  $msg[] =  $data['proCode']."：导入失败<br/>";
                }
            }else{
              $fail++;
              $msg[] =   "第{$i}行导入失败，无产品编号或者产品名称<br/>";
            }

          }
      }

      fclose($fh);
      $msg[] =   "导入产品".($i-1)."条，成功{$success}，失败{$fail}<br/>";

      return array('msg'=>$msg,'success'=>$success,'fail'=>$fail);
  }

  /**
   * 获取产品编号的选择项
   * Time：2020/09/09 12:59:27
   * @author li
   * @param 参数类型
   * @return 返回值类型
  */
  function actionGetOptionsCode(){
    $params = $this->axiosPost();
    $sql = "SELECT * FROM sample_ruku2product where 1";
    if($params['key']){
        $sql .= " and code like '%{$params['key']}%'";
    }
    $sql .= " group by code order by id limit 8";
    $row = $this->_modelExample->findBySql($sql);
    $arr = array();
    foreach($row as & $v){
        $arr[] = array('value'=>$v['code'],'text'=>$v['code'],'kind'=>'ruku');
    }

    if(count($arr) < 8){
        $proCodes = array_col_values($row,'code');
        $limit = 8 - count($arr);
        if($_GET['kindId']){
            $condition[] = array('kindId',$_GET['kindId'],'=');
        }
        $condition[] = array('isSample',1,'=');
        $condition[] = array('proCode',"%{$params['key']}%",'like');
        if(count($proCodes) > 0){
            foreach($proCodes as & $v){
                $v = "'{$v}'";
            }
            $proCodes = join(',' , $proCodes);
            $condition[] = " proCode not in({$proCodes})";
        }

        // dump($condition);
        $row = $this->_modelExample->findAll($condition, 'proCode' ,$limit);
        foreach($row as & $v){
            $arr[] = array('value'=>$v['id'],'text'=>$v['proCode'],'kind'=>'pro');
        }
    }
    echo json_encode(array(
        'success' =>count($arr) > 0,
        'data'    =>$arr
    ));
  }

  function actionGetProduct(){
    $params = $this->axiosPost();
    if($params['id']){
        $pro = $this->_modelExample->find($params['id']);
    }else if($params['proCode']){
        $pro = $this->_modelExample->find(array('proCode'=>$params['proCode']));
    }

    // 给一个产品描述的字符串
    $this->_modelExample->filedValue3($d,$pro);
    foreach ($d as $key => &$v) {
        $pro['productDesc'][] = $key.'：'.$v;
    }
    $pro['productDesc'] = join('，',$pro['productDesc']);
    $pro['productDesc'] = '产品名称：'.$pro['proName'].'，'.$pro['productDesc'];
    //返回
    echo json_encode(array(
        'success' =>$pro['id'] > 0,
        'data'    =>$pro
    ));
  }

  function actionGetProductInfo(){
    $params = $this->axiosPost();
    if($params['id']){
        $pro = $this->_modelExample->find($params['id']);
    }
    if($params['kindId']){
        $row = $this->_modelKind->getFileds($params['kindId']);
    }
    $columns = array();

    if($row['single']){
        foreach ($row['single'] as $k => &$v) {
            $columns[] = $v;
        }
    }
    if($row['default']){
        foreach ($row['default'] as $k => &$v) {
            $columns[] = $v;
        }
    }
    $fileds = array();
    foreach ($columns as $key => $value) {
        $fileds[] = $value['filed'];
    }
    //返回
    echo json_encode(array(
        'success' =>$pro['id'] > 0,
        'data'    =>$pro,
        'columns' =>$fileds
    ));
  }
}
?>